﻿using System.Collections;
using System.Collections.Generic;
using System.Xml;
using System.Xml.Schema;
using System.Xml.Serialization;
using UnityEngine;

public class SerializableDictionary<TKey, TValue> : Dictionary<TKey, TValue>, IXmlSerializable
{
    public XmlSchema GetSchema()
    {
        throw null;
    }

    public void ReadXml(XmlReader reader)
    {
        XmlSerializer xmlKey = new XmlSerializer(typeof(TKey));
        XmlSerializer xmlValue = new XmlSerializer(typeof(TValue));

        reader.Read(); //跳过第一行
        //不是最后一行
        while (reader.NodeType != XmlNodeType.EndElement)
        {
            TKey key = (TKey)xmlKey.Deserialize(reader);
            TValue value = (TValue)xmlValue.Deserialize(reader);
            this.Add(key, value);
        }
    }

    public void WriteXml(XmlWriter writer)
    {
        XmlSerializer xmlKey = new XmlSerializer(typeof(TKey));
        XmlSerializer xmlValue = new XmlSerializer(typeof(TValue));

        foreach (KeyValuePair<TKey, TValue> kv in this)
        {
            xmlKey.Serialize(writer, kv.Key);
            xmlValue.Serialize(writer, kv.Value);
        }

    }
}
